#include "LinkList.h"
// 带头
void InitList(LinkList *L)
{
    *L = (LNode *)malloc(sizeof(LNode));
    (*L)->next_ = NULL;
}
int Length(LinkList *L)
{
    int size = 0;
    LNode *tmp = *L;
    while (tmp->next_)
    {
        size++;
        tmp = tmp->next_;
    }
    return size;
}

void DestroyList(LinkList *L)
{
    LNode *tmp = (*L)->next_;
    while (tmp)
    {
        LNode *next = tmp->next_;
        free(tmp);
        tmp = next;
    }
    free(*L);
    *L = NULL;
}
bool Empty(LinkList *L)
{
    return (*L)->next_ == NULL;
}

LNode *GetElem(LinkList *L, int pos)
{
    LNode *tmp = *L;
    int i = 0;
    while (tmp != NULL && i < pos)
    {
        tmp = tmp->next_;
        i++;
    }
    return tmp;
}
LNode *LocateElem(LinkList *L, DataType val)
{
    LNode *tmp = (*L)->next_;
    while (tmp != NULL && tmp->data_ != val)
        tmp = tmp->next_;
    return tmp;
}

LNode *BuyListNode(DataType val)
{
    LNode *tmp = (LNode *)malloc(sizeof(LNode));
    if (tmp == NULL)
    {
        perror("malloc fail");
    }
    tmp->data_ = val;
    tmp->next_ = NULL;
    return tmp;
}
bool ListInsert(LinkList *L, int pos, DataType val)
{
    if (pos < 1)
        return false;
    int i = 0;
    LNode *tmp = *L;
    while (tmp != NULL && i < pos - 1) // pos>length
    {
        tmp = tmp->next_;
        i++;
    }
    if (tmp == NULL)
        return false;
    LNode *newnode = BuyListNode(val);
    newnode->next_ = tmp->next_;
    tmp->next_ = newnode;
    return true;
}
bool ListDelete(LinkList *L, int pos, DataType *val)
{
    if (pos < 1 || (*L)->next_ == NULL)
        return false;

    LNode *tmp = *L;
    int i = 0;
    while (tmp != NULL && i < pos - 1)
    {
        tmp = tmp->next_;
        i++;
    }
    if (tmp == NULL || tmp->next_ == NULL)
        return false;
    LNode *del = tmp->next_;
    tmp->next_ = del->next_;
    *val = del->data_;
    free(del);
    return true;
}

void PrintList(LinkList *L)
{
    LNode *tmp = (*L)->next_;
    while (tmp)
    {
        printf("%d->", tmp->data_);
        tmp = tmp->next_;
    }
    printf("NULL\n");
}

bool List_headInsert(LinkList *L)
{
    int x = 100;
    while (x)
    {
        LNode *newnode = BuyListNode(x);
        newnode->next_ = (*L)->next_;
        (*L)->next_ = newnode;
        x--;
    }
    return true;
}
bool List_TailInsert(LinkList *L)
{
    int x = 100;
    LNode *r = *L;
    while (x)
    {
        LNode *newnode = BuyListNode(x);
        r->next_ = newnode;
        r = newnode;
        x--;
    }
    return true;
}

// 带头
void Reverse(LinkList *L)
{
    LNode *tmp = (*L)->next_;
    (*L)->next_ = NULL;
    while (tmp)
    {
        LNode *next = tmp->next_;
        tmp->next_ = (*L)->next_;
        (*L)->next_ = tmp;
        tmp = next;
    }
}